<template>
<view>
    detail
    <view class="container3"  >
    <!-- 热门商家列表 -->
    <view class="hot-list">
      <view 
        v-for="(item) in product" 
        :key="item._id" 
        class="shop-card"

        @click="ontext(item._id)" >
     
        <image class="shop-image" :src="item.imgUrl" mode="aspectFill"></image>
        
        <view class="shop-info">
          <view class="shop-name">{{ item.name }}</view>
          <view class="shop-sales">月售 {{ item.sales }} 单</view>
          <view class="shop-delivery">
            <text v-if="item.expressLimit > 0">¥{{ item.expressLimit }}起送</text>
            <text>配送费 ¥{{ item.expressPrice }}</text>
          </view>
          <view class="shop-slogan">{{ item.slogan }}</view>
        </view>

 

      </view>
        <!-- 全部商品-->
      <view class="container">
    <!-- 左侧分类导航 -->

      <view class="left-nav">
      <button 
  @click="currentTab = 'home'" 
  :class="['nav-item', currentTab === 'home' ? 'active' : '']"
>全部商品</button>

<button 
  @click="currentTab = 'list'" 
  :class="['nav-item', currentTab === 'list' ? 'active' : '']"
>秒杀</button>

<button 
  @click="currentTab = 'user'" 
  :class="['nav-item', currentTab === 'user' ? 'active' : '']"
>新鲜水果</button>
    </view>
    
    <!-- 右侧内容区域（暂时留空） -->
    <view class="right-content">
        <view class="content">
      <view v-if="currentTab === 'home'">首页内容 
       <view class="product-container">
    <!-- 商品列表 -->
     
    <view v-for="item in allProducts" :key="item._id" class="product-item">
      <image class="product-image" :src="item.imgUrl" mode="aspectFill"></image>
      <view class="product-info">
        <text class="product-name">{{ item.name }}</text>
        <view class="price-container">
          <text class="current-price">¥{{ item.price }}</text>
          <text class="old-price">¥{{ item.oldPrice }}</text>
        </view>
        <text class="sales">已售 {{ item.sales }}份</text>
      </view>
    <view class="quantity-control">
  <button class="quantity-btn decrease-btn" @click="decrease(item._id)">-</button>
  <view class="quantity-display">{{ getItemCount(item._id) }}</view>
  <button class="quantity-btn increase-btn" @click="increase(item._id)">+</button>
</view>
    </view>
     
  </view>
         <!-- {{allProducts}} -->
       
       
        </view>
      <view v-if="currentTab === 'list'">列表内容
 <view class="product-container">
    <!-- 商品列表 -->
    <view v-for="item in miaosha" :key="item._id" class="product-item">
      <image class="product-image" :src="item.imgUrl" mode="aspectFill"></image>
      <view class="product-info">
        <text class="product-name">{{ item.name }}</text>
        <view class="price-container">
          <text class="current-price">¥{{ item.price }}</text>
          <text class="old-price">¥{{ item.oldPrice }}</text>
        </view>
        <text class="sales">已售 {{ item.sales }}份</text>
      </view>
     <view class="quantity-control">
  <button class="quantity-btn decrease-btn" @click="decrease(item._id)">-</button>
  <view class="quantity-display">{{ getItemCount(item._id) }}</view>
  <button class="quantity-btn increase-btn" @click="increase(item._id)">+</button>
</view>
    </view>
   
  </view>
      </view>
      <view v-if="currentTab === 'user'">用户中心
<view class="product-container">
    <!-- 商品列表 -->
    <view v-for="item in xinxian" :key="item._id" class="product-item">
      <image class="product-image" :src="item.imgUrl" mode="aspectFill"></image>
      <view class="product-info">
        <text class="product-name">{{ item.name }}</text>
        <view class="price-container">
          <text class="current-price">¥{{ item.price }}</text>
          <text class="old-price">¥{{ item.oldPrice }}</text>
        </view>
        <text class="sales">已售 {{ item.sales }}份</text>
      </view>
    <view class="quantity-control">
  <button class="quantity-btn decrease-btn" @click="decrease(item._id)">-</button>
  <view class="quantity-display">{{ getItemCount(item._id) }}</view>
  <button class="quantity-btn increase-btn" @click="increase(item._id)">+</button>
</view>
    </view>
   
  </view>
  
      </view>
      
    </view>
    </view>
    
  </view>
 
  <view class="follow">
    <!-- <view> //此处有个购物车图像，计算的已购商品的总价格一点击购物车图像显示购买的那些商品</view> -->
     <!-- 在底部显示总价 点击购物车向上滑出页面显示购买了哪些商品 -->
     <view style="width:100%,height:100px ,background-color:red">
      <button @click="jisua">商品信息</button> <!--  <view @click="isabled" class="shopped">商品</view> -->
       {{money}}

      <button @click="gocount">去结算</button>

     </view>
     <view v-if="isable">

         <view v-for="item in shangping" :key="item._id" class="product-item">
          <image class="product-image" :src="item.imgUrl" mode="aspectFill"></image>
          <view class="product-info">
            <text class="product-name">{{ item.name }}</text>
            <view class="price-container">
              <text class="current-price">¥{{ item.price }}</text>
              <text class="old-price">¥{{ item.oldPrice }}</text>
            </view>
            <text class="sales">已售 {{ item.sales }}份</text>
            <text class="sales">数量 {{ item.count }}份</text>
          </view>
          </view>
     </view>
     
  </view>
    </view>
    
  </view>
  
  
    </view> 
       
</template>
<script>
export default {
  data() {
    return {
      id: "",
      product: [],
      currentTab: "home",
      alls: [],
      allProducts: [],
      miaosha: [],
      xinxian: [],
      cartItems: [], // 购物车数据
      money: 0,
      isable: false,
      dangqian: [],
      shangping: [],
      token: "",
      a:[]
    }
  },
  
  onShow() {
    this.loadCartItems();
    
  },
  
  onLoad(options) {
    this.id = options.id;
    this.token = uni.getStorageSync('token') || '';
    this.query();
    this.req();
    this.loadCartItems();
  },
  
  methods: {
    // 加载购物车数据（关键修改）
    loadCartItems() {
      const allCartItems = uni.getStorageSync('cartItems') || [];
      this.cartItems = allCartItems.filter(item => item.token === this.token);
      this.shangping = this.cartItems.filter(item => item.shop === this.id);
    },
    
    // 保存购物车数据（关键修改）
    saveCartItems() {
      const allCartItems = uni.getStorageSync('cartItems') || [];
      
      // 1. 先移除当前用户的所有旧数据
      const otherUsersItems = allCartItems.filter(item => item.token !== this.token);
      
      // 2. 合并其他用户的数据和当前用户的新数据
      const updatedCartItems = [...otherUsersItems, ...this.cartItems];
      
      // 3. 保存回本地存储
      uni.setStorageSync('cartItems', updatedCartItems);
    },
    
    jisua() {
      this.isable = !this.isable;
      this.money = 0;
      this.shangping = this.cartItems.filter(item => item.shop === this.id);
      this.shangping.forEach(element => {
        this.money += element.price * element.count;
      });
      console.log('当前商店总价:', this.money);
    },

  gocount() {
  // 1. 确保数据是最新的
  this.shangping = this.cartItems.filter(item => item.shop === this.id);
  
  // 2. 同步到本地存储（确保数据已准备）
  uni.setStorageSync('a', this.shangping);
  
  // 3. 跳转支付页
  uni.navigateTo({
    url: '/pages/pay/pay',
    success: () => {
      console.log('跳转成功，数据已同步:', this.shangping);
    }
  });
},
    
    query() {
      uni.request({
        url: 'http://localhost:3000/hotlist?_id=' + this.id,
        method: 'GET',
        success: (res) => {
          this.product = res.data;
        }
      });
    },
    
    req() {
      uni.request({
        url: 'http://localhost:3000/all',
        method: 'GET',
        success: (res) => {
          console.log('请求成功haha:' + JSON.stringify(res.data));
          this.alls = res.data;
          const shop1Data = this.alls.filter(item => item.shop === this.id);
          this.allProducts = shop1Data.map(item => item.text);
          
          const shop1Data2 = this.alls.filter(item => item.text.type2 === '1')
                                      .filter(item => item.shop === this.id);
          this.miaosha = shop1Data2.map(item => item.text);
          
          const shop1Data3 = this.alls.filter(item => item.text.type === '1')
                                      .filter(item => item.shop === this.id);
          this.xinxian = shop1Data3.map(item => item.text);
        }
      });
    },
    
    getItemCount(_id) {
      const item = this.cartItems.find(item => item._id === _id);
      return item ? item.count : 0;
    },
    
    increase(_id) {
      this.updateCount(_id, 1);
    },
    
    decrease(_id) {
      this.updateCount(_id, -1);
    },
    
    // 更新数量（核心方法，关键修改）
    async updateCount(_id, change) {
      try {
        const index = this.cartItems.findIndex(item => item._id === _id);
        
        if (index >= 0) {
          // 更新现有商品数量
          this.cartItems[index].count += change;
          
          if (this.cartItems[index].count <= 0) {
            // 数量为0时移除商品
            this.cartItems.splice(index, 1);
          }
        } else if (change > 0) {
          // 添加新商品到购物车
          const product = [...this.allProducts, ...this.miaosha, ...this.xinxian]
                          .find(p => p._id === _id);
          
          if (product) {
            this.cartItems.push({
              ...product,
              count: 1,
              shop: this.id,
              token: this.token  // 关键：添加用户标识
            });
          }
        }
        
        // 保存到本地存储
        this.saveCartItems();
        
        // 更新服务器数据
        uni.request({
          url: `http://localhost:3000/all/`,
          method: 'PATCH',
          data: {
            count: this.cartItems.find(item => item._id === _id)?.count || 0
          },
          success: (res) => {
            if (res.statusCode === 200) {
              uni.showToast({ title: '更新成功', icon: 'success' });
            }
          },
          fail: (err) => {
            console.error('请求失败:', err);
          }
        });
        
      } catch (error) {
        console.error('更新数量失败:', error);
        uni.showToast({ title: '更新失败', icon: 'none' });
      }
    }
  }
}

</script>
<style scoped>
/* 基础样式重置 */
/* 数量控制器 - 优化版 */


.quantity-control {
  display: flex;
  align-items: center;
  margin-left: auto;
}

/* 加减按钮基础样式 */
.quantity-btn {
    background-color: #f5f5f5;
  color: #666;
}

/* 减号按钮 */
.decrease-btn {
  background-color: #f5f5f5;
  color: #666;
}

.decrease-btn:active {
  background-color: #e5e5e5;
  transform: scale(0.95);
}



/* 数量显示 */
.quantity-display {
  min-width: 60rpx;
  text-align: center;
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}




/* 禁用状态 */
.quantity-btn[disabled] {
  opacity: 0.5;
  pointer-events: none;
}


page {
  background-color: #f8f8f8;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
  color: #333;
  line-height: 1.5;
}

/* 主容器 */
.container3 {
  padding: 20rpx;
  background-color: #f8f8f8;
  width: 100%;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 商家卡片样式 */
.hot-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.shop-card {
  display: flex;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.shop-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.shop-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.shop-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.shop-sales {
  font-size: 24rpx;
  color: #999;
}

.shop-delivery {
  display: flex;
  gap: 20rpx;
  font-size: 24rpx;
  color: #666;
}

.shop-slogan {
  font-size: 24rpx;
  color: #ff6a6c;
  background-color: #fff2f0;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
  align-self: flex-start;
}

/* 分类导航 */
.container {
  display: flex;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  margin-bottom: 20rpx;
}

.left-nav {
  width: 180rpx;
  background-color: #f5f5f5;
}

.nav-item {
  padding: 24rpx 0;
  font-size: 26rpx;
  color: #666;
  text-align: center;
  border: none;
  background: none;
  position: relative;
  line-height: 1.4;
}

.nav-item::after {
  content: '';
  position: absolute;
  left: 20rpx;
  right: 20rpx;
  bottom: 0;
  height: 1rpx;
  background-color: #eee;
}

.nav-item.active {
  color: #07c160;
  background-color: #fff;
  font-weight: 500;
}

.nav-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 6rpx;
  background-color: #07c160;
}

.right-content {
  flex: 1;
  padding: 20rpx;
}

/* 商品列表 */
.product-container {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.product-item {
  display: flex;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
}

.product-image {
  width: 140rpx;
  height: 140rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
}

.price-container {
  display: flex;
  align-items: center;
  margin-top: 10rpx;
}

.current-price {
  font-size: 32rpx;
  color: #f44;
  font-weight: 600;
}

.old-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
  margin-left: 10rpx;
}

.sales {
  font-size: 24rpx;
  color: #999;
  margin-top: 6rpx;
}

/* 数量控制器 */
.quantity-control {
  display: flex;
  align-items: center;
  margin-left: auto;
}

.quantity-control button {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 10rpx;
  border: none;
  font-size: 28rpx;
  color: #666;
}

.quantity-control text {
  min-width: 40rpx;
  text-align: center;
  font-size: 28rpx;
}

/* 购物车底部栏 */
.cart-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20rpx;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.08);
  z-index: 100;
}

.cart-total {
  font-size: 32rpx;
  font-weight: 600;
  color: #f44;
}

.checkout-btn {
  background-color: #07c160;
  color: #fff;
  border-radius: 40rpx;
  padding: 0 40rpx;
  height: 72rpx;
  line-height: 72rpx;
  font-size: 28rpx;
  border: none;
}

/* 购物车弹窗 */
.cart-popup {
  position: fixed;
  bottom: 100rpx;
  left: 0;
  right: 0;
  background-color: #fff;
  max-height: 60vh;
  overflow-y: auto;
  padding: 20rpx;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.08);
  border-radius: 24rpx 24rpx 0 0;
  z-index: 99;
}

/* 响应式调整 */
/* @media (max-width: 480px) {
  .shop-image {
    width: 100rpx;
    height: 100rpx;
  }
  
  .left-nav {
    width: 160rpx;
  }
  
  .product-image {
    width: 120rpx;
    height: 120rpx;
  }
} */

</style>